package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.annotation.AutoFill;
import com.hmall.item.constant.MqConstants;
import com.hmall.item.enumeration.OperationType;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    //分页查询
    @GetMapping("/list")
    public PageDTO<Item> PageQuery(@RequestParam("page") Integer page,@RequestParam("size") Integer size){
        Page<Item> result = itemService.page(new Page<>(page, size));
        PageDTO<Item> itemPageDTO = new PageDTO<>(result.getTotal(), result.getRecords());
        return itemPageDTO;
    }

    //根据id查询商品
    @GetMapping("/{id}")
    public Item selectById(@PathVariable("id") Long id){
        return itemService.getById(id);
    }


    //新增商品
    @PostMapping
    @AutoFill(value = OperationType.INSERT)
    public void insert(@RequestBody Item item){
        item.setStatus(2);
        itemService.save(item);
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //上架 下架
    @PutMapping("/status/{id}/{status}")
    public void updateStatusItem(@PathVariable("id") Long id,@PathVariable("status") Integer status){
        itemService.update().set("status",status).eq("id",id).update();
        String routingKey = status == MqConstants.UP_STATUS ? MqConstants.ITEM_UP:MqConstants.ITEM_DOWN;
        rabbitTemplate.convertAndSend(MqConstants.ITEM_TOPIC,routingKey,id);

    }


    //修改商品
    @PutMapping
    public void updateItem(@RequestBody Item item){
        item.setUpdateTime(new Date());
        item.setStatus(null);//更新时状态是不可以被修改的
        itemService.updateById(item);
    }

    //根据id进行删除
    @DeleteMapping("/{id}")
    public void deleteItem(@PathVariable("id") Long id){
        itemService.removeById(id);
    }
}
